import { defineEventHandler, getQuery } from 'h3';
import { MOCK_VISITORS } from '~/utils/mock-data';
import { useResponseSuccess } from '~/utils/response';

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const page = Number.parseInt(query.page as string) || 1;
  const pageSize = Number.parseInt(query.pageSize as string) || 10;
  const status = query.status as string | undefined;
  const search = query.search as string | undefined;
  const isCollected = query.isCollected as string | undefined;
  const profession = query.profession as string | undefined;
  const expertise = query.expertise as string | undefined;
  const skills = query.skills as string | undefined;
  const experience = query.experience as string | undefined;
  const gender = query.gender as string | undefined;

  let filteredVisitors = MOCK_VISITORS;

  // 状态筛选
  if (status && status !== 'all' && status !== 'undefined') {
    filteredVisitors = filteredVisitors.filter((v) => v.status === status);
  }

  // 收藏状态筛选
  if (isCollected === 'true') {
    filteredVisitors = filteredVisitors.filter((v) => v.isCollected);
  }

  // 职业筛选
  if (profession && profession !== '不限' && profession !== 'undefined') {
    filteredVisitors = filteredVisitors.filter(
      (v) => v.profession === profession,
    );
  }

  // 擅长领域筛选
  if (expertise && expertise !== '不限' && expertise !== 'undefined') {
    filteredVisitors = filteredVisitors.filter((v) =>
      v.expertise.includes(expertise),
    );
  }

  // 技能标签筛选
  if (skills && skills !== '不限' && skills !== 'undefined') {
    filteredVisitors = filteredVisitors.filter((v) =>
      v.skills.includes(skills),
    );
  }

  // 经验筛选
  if (experience && experience !== '不限' && experience !== 'undefined') {
    filteredVisitors = filteredVisitors.filter(
      (v) => v.experience === experience,
    );
  }

  // 性别筛选
  if (gender && gender !== '不限' && gender !== 'undefined') {
    filteredVisitors = filteredVisitors.filter((v) => v.gender === gender);
  }

  // 搜索筛选
  if (search && search.trim() !== '') {
    const lowerCaseSearch = search.toLowerCase();
    filteredVisitors = filteredVisitors.filter(
      (v) =>
        v.name.toLowerCase().includes(lowerCaseSearch) ||
        v.profession.toLowerCase().includes(lowerCaseSearch) ||
        v.city.toLowerCase().includes(lowerCaseSearch) ||
        v.expertise.some((e) => e.toLowerCase().includes(lowerCaseSearch)) ||
        v.skills.some((s) => s.toLowerCase().includes(lowerCaseSearch)),
    );
  }

  const total = filteredVisitors.length;
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedVisitors = filteredVisitors.slice(startIndex, endIndex);

  return useResponseSuccess({
    list: paginatedVisitors,
    total,
    page,
    pageSize,
  });
});
